#include "./fiipChecking.h"
#define CHECKDUPLICATE_MAXLEN 20
static FiipCheckDuplicateStruct checkDuplicateList[CHECKDUPLICATE_MAXLEN];
static uint8_t checkDuplicateListLen = 0;

int8_t fiipChecking_isDuplicate(Format_FieldStruct* msg) {
  FiipCheckDuplicateStruct* checkDuplicate = NULL;
  uint16_t index = (msg->index[0] << 8) | msg->index[1];
  uint16_t cmd = (msg->cmd[0] << 8) | msg->cmd[1];
  uint16_t dataCRC = getCrc16(msg->body, (msg->len[0] << 8) | msg->len[1]);
  for (int i = 0; i < CHECKDUPLICATE_MAXLEN; i++) {
    checkDuplicate = &checkDuplicateList[i];
    if (checkDuplicate->index == index && checkDuplicate->cmd == cmd &&
        checkDuplicate->dataCRC == dataCRC) {
      if (mem_cmp(msg->srcAddr, checkDuplicate->devAddr, 8) == 0) {
        return 1;
      }
    }
  }

  if (checkDuplicateListLen >= CHECKDUPLICATE_MAXLEN) {
    checkDuplicateListLen = 0;
  }
  checkDuplicate = &checkDuplicateList[checkDuplicateListLen++];
  checkDuplicate->devAddr = mempool_alloc(8);
  mem_cpy(checkDuplicate->devAddr, msg->srcAddr, 8);
  checkDuplicate->index = index;
  checkDuplicate->cmd = cmd;
  checkDuplicate->dataCRC = dataCRC;
  return 0;
}
